import { defineConfig, loadEnv } from 'vite'
import path from 'node:path'
import uni from '@dcloudio/vite-plugin-uni'
import AutoImport from 'unplugin-auto-import/vite'
import UnoCSS from 'unocss/vite'
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import viteCompression from 'vite-plugin-compression'
import resolve from '@rollup/plugin-node-resolve';

// https://vitejs.dev/config/
export default ({ command, mode }) => {
  const env = loadEnv(mode, path.resolve(process.cwd()))
  const { VITE_APP_API_BASEURL, VITE_APP_PROXY, VITE_APP_PROXY_PREFIX, VITE_APP_PORT } = env
  const alias = {
    '~': `${path.resolve(__dirname, './')}`,
    '@': `${path.resolve(__dirname, 'src')}`
  }
  return defineConfig({
    server: {
      host: '0.0.0.0',
      hmr: true,
      port: VITE_APP_PORT,
      // 仅 H5 端生效，其他端不生效（其他端走build，不走devServer)
      proxy: JSON.parse(VITE_APP_PROXY)
        ? {
            [VITE_APP_PROXY_PREFIX]: {
              target: VITE_APP_API_BASEURL,
              changeOrigin: true,
              rewrite: (path) => path.replace(new RegExp(`^${VITE_APP_PROXY_PREFIX}`), '')
            }
          }
        : undefined
    },
    resolve: {
      alias
    },
    // 解决警告You are running the esm-bundler build of vue-i18n.
    define: {
      __VUE_I18N_FULL_INSTALL__: true,
      __VUE_I18N_LEGACY_API__: true,
      __VUE_I18N_PROD_DEVTOOLS__: true,
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true
    },
    build: {
      // rollupOptions 允许你覆盖 Rollup 的默认配置，Rollup 是 Vite 用于生产构建的打包器。你可以通过此选项来调整依赖打包的行为。
      rollupOptions: {
        // 示例：禁用某些 Rollup 插件
        plugins: [],
        // 示例：调整输出配置
        output: {
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia']
          }
        },
        // 示例：调整输入配置
        input: {}
      }
    },
    plugins: [
      resolve(),
      UniManifest(),
      uni(),
      viteCompression(),
      vueSetupExtend(),
      AutoImport({
        imports: [
          'vue',
          'uni-app',
          'pinia',
          {
            '@/api': ['useRequest']
          }
        ],
        eslintrc: { enabled: true }
      }),
      UnoCSS()
    ],
    // css:{},
    optimizeDeps: {
      // 开发时 解决这些commonjs包转成esm包
      include: [
        '@jiaminghi/c-render',
        '@jiaminghi/c-render/lib/plugin/util',
        '@jiaminghi/charts/lib/util/index',
        '@jiaminghi/charts/lib/util',
        '@jiaminghi/charts/lib/extend/index',
        '@jiaminghi/charts',
        '@jiaminghi/color'
      ]
    }
  })
}
